#!/bin/bash
########################################################################
# script name:  remove_user_from_group.sh
# Used for:
# Author:       Martin Dumont
# Contributors:
# Version:      0.1
#
# (date format: date +'%Y/%m/%d')
#
# Date          Version Contributors    Modifications
# ----------    ------- ------------    -------------
# 2012/03/02    0.1     MDUMONT         initial
########################################################################
usage()
{
cat << STOP

usage: $0 [options] [ARG]

This script is used for ....

OPTIONS:
   -h               All hosts (detail output)
   -u               User to remove
   -g               Group to remove user from

Ex.:
$0 -h saprmt02 -u b0523345 -g admin
STOP
}
#######################################
# Get parameters
#######################################
while getopts h:u:g: OPTION
do
        case $OPTION in
        h)
                HOSTS=$(echo $OPTARG | tr '[A-Z]' '[a-z]' | sed 's/,/ /g')
                ;;
        u)
                MYUSERS=$(echo $OPTARG | tr '[A-Z]' '[a-z]' | sed 's/,/ /g')
                ;;
        g)
                MYGROUP=$(echo $OPTARG | tr '[A-Z]' '[a-z]' | sed 's/,/ /g')
                ;;
        \?)
                usage
                exit 1
                ;;
        *)
                usage
                exit 1
                ;;
        esac
done
if [ $OPTIND = 1 ]; then usage; exit 1; fi
if [ -z "$HOSTS" ]; then HOSTS=localhost; fi
if [ -z "$MYUSERS" ]; then usage; exit 1; fi
if [ -z "$MYGROUP" ]; then usage; exit 1; fi
#######################################
# Variables and environnement
#######################################
SSH_OPTS=" -o ConnectTimeout=15 -o BatchMode=yes -o StrictHostKeyChecking=no -o LogLevel=quiet"
BAENV=$(dirname `which $0`)/loadenv.sh
if [ -f $BAENV ]; then . $BAENV; else echo "No env library ($BAENV)"; exit 1; fi
NEWHOSTLIST=$(checkhost $HOSTS | grep -v Verifying)
#######################################
# MAIN
#######################################
for HOSTNAME in $NEWHOSTLIST
do
	for MYUSER in $MYUSERS
	do
		cat <<-EOF | if [ "$HOSTNAME" != "localhost" ]; then sudo -u saunix ssh $SSH_OPTS $HOSTNAME "cat | sudo bash"; else cd /tmp; cat | sudo bash; fi
			if ! cat /etc/passwd | grep -q $MYUSER
			then
				echo "User $MYUSER doesn't exist on \`uname -n\`"
			else
				MYGROUPS=\`id -nG $MYUSER\`
				NEWGROUPS=\`echo \$MYGROUPS | tr ' ' '\n' | grep -v $MYGROUP | tr '\n' ','\ | sed 's/,$//'\`
				if echo \$MYGROUPS  | cut -d' ' -f1 | \grep -q $MYGROUP; then echo changing primary group to staff; usermod -g staff $MYUSER; fi
				if echo \$MYGROUPS | \grep -q $MYGROUP; then echo Removing $MYUSER from group $MYGROUP; usermod -G \$NEWGROUPS $MYUSER; fi
			fi
		EOF
	done
done
#######################################
exit 0
